const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📝 记录用户登录日志')
  
  try {
    const { OPENID, APPID, UNIONID } = cloud.getWXContext()
    const {
      loginType = 'wechat', // 登录类型：wechat, anonymous
      deviceInfo = {},      // 设备信息
      locationInfo = {},    // 位置信息
      userInfo = {},        // 用户信息
      source = 'unknown',   // 触发来源：launch, show, manual
      description = ''      // 操作描述
    } = event
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 获取用户IP地址（从云函数环境中获取）
    const clientIP = context.requestContext?.sourceIp || 'unknown'
    
    // 创建登录日志记录
    const loginLog = {
      openid: OPENID,
      unionid: UNIONID || '',
      appid: APPID || '',
      loginType: loginType,
      loginTime: new Date(),
      clientIP: clientIP,
      deviceInfo: {
        platform: deviceInfo.platform || 'unknown',
        system: deviceInfo.system || 'unknown',
        version: deviceInfo.version || 'unknown',
        model: deviceInfo.model || 'unknown',
        brand: deviceInfo.brand || 'unknown',
        screenWidth: deviceInfo.screenWidth || 0,
        screenHeight: deviceInfo.screenHeight || 0,
        pixelRatio: deviceInfo.pixelRatio || 1
      },
      locationInfo: {
        province: locationInfo.province || '',
        city: locationInfo.city || '',
        country: locationInfo.country || '',
        latitude: locationInfo.latitude || 0,
        longitude: locationInfo.longitude || 0
      },
      userInfo: {
        nickName: userInfo.nickName || '',
        avatarUrl: userInfo.avatarUrl || '',
        gender: userInfo.gender || 0,
        language: userInfo.language || '',
        country: userInfo.country || '',
        province: userInfo.province || '',
        city: userInfo.city || ''
      },
      sessionId: generateSessionId(),
      userAgent: context.requestContext?.userAgent || '',
      source: source, // 记录触发来源
      description: description, // 操作描述
      createTime: new Date()
    }
    
    console.log('📋 登录日志数据:', {
      openid: OPENID,
      loginType: loginType,
      clientIP: clientIP,
      platform: deviceInfo.platform
    })
    
    // 插入登录日志
    const result = await db.collection('user_login_logs').add({
      data: loginLog
    })
    
    console.log('✅ 登录日志记录成功:', result._id)
    
    // 更新用户最后登录时间
    try {
      await updateUserLastLogin(OPENID, loginLog)
    } catch (updateError) {
      console.warn('⚠️ 更新用户最后登录时间失败:', updateError)
    }
    
    // 清理过期的登录日志（保留最近30天）
    try {
      await cleanupOldLogs()
    } catch (cleanupError) {
      console.warn('⚠️ 清理过期日志失败:', cleanupError)
    }
    
    return {
      success: true,
      message: '登录日志记录成功',
      data: {
        logId: result._id,
        loginTime: loginLog.loginTime,
        sessionId: loginLog.sessionId
      }
    }
    
  } catch (error) {
    console.error('❌ 记录登录日志失败:', error)
    return {
      success: false,
      error: error.message || '记录登录日志失败'
    }
  }
}

// 生成会话ID
function generateSessionId() {
  const timestamp = Date.now().toString(36)
  const randomStr = Math.random().toString(36).substring(2, 8)
  return `${timestamp}_${randomStr}`
}

// 更新用户最后登录时间
async function updateUserLastLogin(openid, loginLog) {
  console.log('🔄 更新用户最后登录时间')
  
  try {
    // 查找用户记录
    const userResult = await db.collection('users')
      .where({ openid: openid })
      .get()
    
    const userData = {
      openid: openid,
      lastLoginTime: loginLog.loginTime,
      lastLoginIP: loginLog.clientIP,
      lastDeviceInfo: loginLog.deviceInfo,
      loginCount: 1,
      updateTime: new Date()
    }
    
    if (userResult.data.length > 0) {
      // 更新现有用户记录
      const user = userResult.data[0]
      userData.loginCount = (user.loginCount || 0) + 1
      
      await db.collection('users')
        .doc(user._id)
        .update({
          data: {
            lastLoginTime: userData.lastLoginTime,
            lastLoginIP: userData.lastLoginIP,
            lastDeviceInfo: userData.lastDeviceInfo,
            loginCount: userData.loginCount,
            updateTime: userData.updateTime
          }
        })
      
      console.log('✅ 用户登录信息更新成功')
    } else {
      // 创建新用户记录
      userData.createTime = new Date()
      userData.userInfo = loginLog.userInfo
      
      await db.collection('users').add({
        data: userData
      })
      
      console.log('✅ 新用户记录创建成功')
    }
    
  } catch (error) {
    console.error('❌ 更新用户最后登录时间失败:', error)
    throw error
  }
}

// 清理过期的登录日志
async function cleanupOldLogs() {
  console.log('🧹 清理过期登录日志')
  
  try {
    const thirtyDaysAgo = new Date()
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
    
    const result = await db.collection('user_login_logs')
      .where({
        loginTime: db.command.lt(thirtyDaysAgo)
      })
      .remove()
    
    if (result.stats.removed > 0) {
      console.log(`🗑️ 清理了 ${result.stats.removed} 条过期登录日志`)
    }
    
  } catch (error) {
    console.error('❌ 清理过期日志失败:', error)
    throw error
  }
}
